package JPetStore.web.servlet;

import JPetStore.domain.Account;
import JPetStore.domain.Item;
import JPetStore.service.CatalogService;
import JPetStore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class ViewItemServlet extends HttpServlet {
    private static final String VIEW_ITEM = "/WEB-INF/jsp/catalog/item.jsp";
    private String itemId;

    public ViewItemServlet() {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.itemId = req.getParameter("itemId");
        CatalogService service = new CatalogService();
        Item item = service.getItem(this.itemId);
        HttpSession session = req.getSession();
        session.setAttribute("item", item);
        Account account = (Account) session.getAttribute("account");
        if (account != null) {
            String username = account.getUsername();
            String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                    + req.getContextPath() + req.getServletPath() + "?" + (req.getQueryString());
            LogService logService = new LogService();
            String logInfo = logService.logInfo(new Object[]{" "}) + strBackUrl + "查看了商品"+this.itemId;
            logService.insertLogInfo(username, logInfo);
        }
        req.getRequestDispatcher(VIEW_ITEM).forward(req, resp);
    }
}
